import {
  inject,
  observer,
} from 'mobx-react';

import {
  Row,
  Col,
  Form,
  Steps,
  Button,
  message,
} from 'antd'

import {
  WeaTop,
  WeaTab,
  WeaTools,
  WeaInput,
  WeaDialog,
  WeaFormItem,
  WeaTableEdit,
  WeaRightMenu,
  WeaDialogFooter,
  WeaLocaleProvider,
} from 'ecCom'
import {
  i18n
} from '../public/i18n';
import React from 'react'
import * as mobx from 'mobx'
import '../style/password.css';
import SecondaryVerify from './secondaryVerify/SecondaryVerify.js'
import {
  RSAEcrypt
} from "../util/RSAUtil";
import {
  checkWeakPass
} from "../util/PASSUtil.js";

const getLabel = WeaLocaleProvider.getLabel;

const Step = Steps.Step;
const toJS = mobx.toJS;
const FormItem = Form.Item;

@inject('hrmPassword')

@observer
class Password extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      oldVal: '',
      newVal: '',
      confirmVal: '',
      verifyCode: '',
      minPassLen: 1,
      passwordComplexity: '0',
      pwd: '',
      tip: '',
      date: new Date().getTime(),
      height: 460,
    }
  }
  
  componentDidMount() {
    const {
      hrmPassword
    } = this.props;
    hrmPassword.getSecuritySettingStatus();
    hrmPassword.isOpenSecondaryPwd();
    this.init();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.resetPwdField();
    }
  }

  init() {
    const {
      hrmPassword
    } = this.props;
    const hrmId = this.props.params.hrmId || '';
    hrmPassword.hrmId = hrmId;
    WeaTools.callApi('/api/hrm/password/getPasswordSetting', 'GET', {
      id: hrmId
    }).then((data) => {
      this.setState({
        passwordComplexity: data.passwordComplexity,
        minPassLen: data.minpasslen,
        openRSA:data.openRSA
      });
      if (data.passwordComplexity == '1') {
        this.setState({
          tip: getLabel('24080', "字母大写、字母小写、数字组合")
        });
      }
      if (data.passwordComplexity == '2') {
        this.setState({
          tip: getLabel('24081', "字母、数字、特殊字符组合")
        });
      }
      if (data.passwordComplexity == '3') {
        this.setState({
          tip: getLabel('512563', "字母、数字组合")
        });
      }
      hrmPassword.hrmId = data.hrmId;
    });
    const {
      tabKey
    } = this.props.location.query;
    if (tabKey) {
      hrmPassword.tabKey = tabKey
    } else {
      hrmPassword.tabKey = '0';
    }
    //加载公钥
    loadjs.isDefined('rsa') ? loadjs.ready('rsa', () => {

    }) : loadjs(["/js/rsa/jsencrypt.js", "/js/rsa/rsa.js"], 'rsa', {
      async: false
    });

    const doUserSession = this.props.location&&this.props.location.query&&this.props.location.query.doUserSession;
    if(hrmPassword.tabKey=='0'&&doUserSession=='1'){
      message.info(getLabel('81626',"首次登录需修改密码！"));
    }
  }

  pwdSave() {
    const {
      oldVal,
      newVal,
      confirmVal,
      verifyCode,
      openRSA
    } = this.state;
    const {
      minPassLen,
      passwordComplexity
    } = this.state;
    if (!oldVal || !newVal || !confirmVal || !verifyCode) {
      message.error(getLabel('386497', "必填信息不完整！"));
      return false
    }

    let RSAParam = {
      'passwordold': oldVal,
      'passwordnew': newVal,
    }
    RSAEcrypt(openRSA,RSAParam).then(RSAParam => {
      const hrmId = this.props.params.hrmId || '';
      const dialogId = this.props.location.query.dialogId || '';
      const optype = this.props.location.query.optype || '';
      let params = {
        'id': hrmId,
        'passwordold': RSAParam.passwordold,
        'passwordnew': RSAParam.passwordnew,
        'validatecode': verifyCode,
        'optype':optype,
      }

      let result = this.newPwdVerification(newVal, confirmVal, minPassLen, passwordComplexity);
      if (result) {
         checkWeakPass(RSAParam.passwordnew,()=>{
            WeaTools.callApi('/api/hrm/password/changePassword', 'POST', params).then(data => {
              if (data.status == '1') {
                message.success(data.message);
                if (dialogId != '') {
                  setTimeout(() => {
                    let dialog = top.window.getParentDialog();
                    if (!dialog) {
                      if (dialogId && window.top.window.dialogMapper && window.top.window.dialogMapper[dialogId]) {
                        dialog = window.top.window.dialogMapper[dialogId];
                      }
                    }
                    this.resetPwdField();
                    dialog.close(); // 关闭。 会触发onCancel
                  }, 3000);
                } else {
                  this.resetPwdField();
                  const doUserSession = this.props.location&&this.props.location.query&&this.props.location.query.doUserSession;
                  if(doUserSession=='1'){
                    window.location.href = '/wui/index.html#/main';
                    return;
                  }
                }
              } else {
                message.error(data.message);
              }
              this.setState({
                date: new Date()
              });
            })

         },()=>{
            this.setState({
              date: new Date()
            })
          })

      }
    });
  }

  resetPwdField() {
    this.setState({
      oldVal: '',
      newVal: '',
      confirmVal: '',
      verifyCode: '',
    });
  }

  newPwdVerification(newVal, confirmVal, minPassLen, passwordComplexity) {
    let checkpass = true;
    if (newVal !== confirmVal) {
      message.error(getLabel('386508', "密码确认不正确！"));
      return false
    } else {
      if (newVal.length < minPassLen) {
        message.error(getLabel('20172', "密码长度不能小于") + minPassLen);
        return false;
      } else {
        if (passwordComplexity == "1") {
          const complexity11 = /[a-z]+/;
          const complexity12 = /[A-Z]+/;
          const complexity13 = /\d+/;

          if (complexity11.test(newVal) && complexity12.test(newVal) && complexity13.test(newVal)) {
            checkpass = true;
          } else {
            message.error(getLabel('512768',"新密码不符合要求，必须包含字母大写、字母小写、数字！请重新输入！"));
            checkpass = false;
          }
        } else if (passwordComplexity == "2") {
          const complexity21 = /[a-zA-Z_]+/;
          const complexity22 = /\W+/;
          const complexity23 = /\d+/;
          if (complexity21.test(newVal) && complexity22.test(newVal) && complexity23.test(newVal)) {
            checkpass = true;
          } else {
            message.error(getLabel('512769',"新密码不符合要求，必须包含字母、数字、特殊字符！请重新输入！"));
            checkpass = false;
          }
        } else if (passwordComplexity == "3") {
          const complexity31 = /[a-zA-Z_]+/;
          const complexity32 = /\d+/;
          if (complexity31.test(newVal) && complexity32.test(newVal)) {
            checkpass = true;
          } else {
            message.error(getLabel('512767', "新密码不符合要求，必须包含字母、数字！请重新输入！"));
            checkpass = false;
          }
        }
      }
      return checkpass;
    }
  }

  getPwdModificationGrid() {
    const {
      oldVal,
      newVal,
      confirmVal,
      verifyCode,
      tip,
      date,
    } = this.state;
    const dialogId = this.props.location.query.dialogId || '';

    return (
      <div>
  				<div style={{marginTop: '60px'}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@zovp8c`}
              label={getLabel('32738',"旧密码")}
              labelCol={{span: 3, offset: 6}}
              wrapperCol={{span: 7}}
            >
              <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@6pvv39`} 
                type="password" 
                viewAttr='3' 
                value={oldVal} 
                onChange={(val) => this.setState({oldVal: val})} 
              />
            </WeaFormItem>
  				</div>
  				<div style={{marginTop: '35px'}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@cjmvod`}
              label={getLabel('27303',"新密码")}
              labelCol={{span: 3, offset: 6}}
              wrapperCol={{span: 7}}
            >
              <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@g1lm3j`} 
                type="password" 
                viewAttr='3' 
                passwordStrength 
                tip={tip}
                value={newVal} 
                onChange={(val) => this.setState({newVal: val})} 
              />
            </WeaFormItem>
  				</div>
  				<div style={{marginTop: '35px'}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@3fgd3h`}
              label={getLabel('32739',"确认新密码")}
              labelCol={{span: 3, offset: 6}}
              wrapperCol={{span: 7}}
            >
              <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@z27cbb`} 
                type="password" 
                viewAttr='3' 
                value={confirmVal} 
                onChange={(val) => this.setState({confirmVal: val})} 
              />
            </WeaFormItem>
  				</div>
          <div style={{marginTop: '35px'}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jd9mwb`}
              label={getLabel('130021',"验证码")}
              labelCol={{span: 3, offset: 6}}
              wrapperCol={{span: 7}}
            >
              <div style={{width:'170%'}}>
                <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@xa1ojh`} 
                  viewAttr='3' 
                  value={verifyCode} 
                  style={{width:'58.9%',float:'left'}}
                  onChange={(val) => this.setState({verifyCode: val})} 
                />
                <img                   
				  src={`/weaver/weaver.file.MakeValidateCode?from=_changePass&isView=1&validatetype=0&validatenum=4&seriesnum_=${date}`}
                  style={{cursor:'pointer',display:'block',float:'left',marginLeft: 25}} 
                  onClick={() => this.setState({date: new Date().getTime()})}
                />
              </div>
            </WeaFormItem>
          </div>
          {dialogId !='' && <WeaDialogFooter ecId={`${this && this.props && this.props.ecId || ''}_WeaDialogFooter@rw3r1z`} buttons={<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1fspc7`} type="primary" onClick={() => this.pwdSave()}>{i18n.button.save()}</Button>} />}
  			</div>
    )
  }

  getPwdSettingContent() {
    const {
      hrmPassword
    } = this.props;
    const {
      isSetted
    } = hrmPassword;
    return (
      <div style={{position: 'relative'}}>
          <div style={{position: 'absolute', left: '50%', top: 50, marginLeft: -337}}>
            <div style={{float: 'left', width: 265}}>
              <img src='/hrm/hrm_e9/image/computer.png' alt=''/>
            </div>
            <div style={{float: 'left', width: 410}}>
              { isSetted ? this.pwdSecurityStatus() : this.pwdSettingIllustration()}  
            </div>
          </div>
        </div>

    )
  }

  pwdSecurityStatus() {
    const {
      hrmPassword
    } = this.props;
    const {
      secStatus
    } = hrmPassword;
    const {
      pwd
    } = this.state;
    return (
      <div style={{marginTop: '30px'}}>
  				<p style={{marginBottom: '12px', fontWeight: 'bold'}}><span style={{fontSize: '14px'}}>{getLabel('386526',"密保状态")}：</span><span style={{fontSize: '13px',color: '#2DB7F5'}}>{secStatus ? getLabel('387099','已启用')  : getLabel('387100','已停用')}</span></p>
  				<p style={{marginBottom: '12px'}}>• {getLabel('386509',"密保问题忘了怎么办？")}</p>
  				<p style={{marginBottom: '12px'}}>{getLabel('386510',"可采用发送短信或发送邮件方式找回密码,若这两种方式都未开启，则联系系统管理员解决。")}</p>
  				<div style={{marginTop: '35px'}}>
  					<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2radb2`} type='primary' onClick={() => {hrmPassword.doOpen('1');hrmPassword.isModifyBtnClick = false}}>{secStatus ? getLabel('26471',"停用") : getLabel('26472',"启用")}</Button>
  					{secStatus ? <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@r5gjck`} type='primary' onClick={() => {hrmPassword.doOpen('1');hrmPassword.isModifyBtnClick = true}} style={{marginLeft: '30px'}}>{getLabel('103',"修改")}</Button>
  										: ''}
  				</div>
  			</div>
    )
  }

  pwdSettingIllustration() {
    const {
      hrmPassword
    } = this.props;
    return (
      <div style={{marginTop: '30px'}}>
  				<p style={{marginBottom: '12px'}}>• {getLabel('386511',"什么是密保问题？")}</p>
  				<p style={{marginBottom: '12px'}}>{getLabel('506872',"由用户设定的几个问题及对应答案组成，用于找回E-cology登录密码。")}</p>
  				<p style={{marginBottom: '12px'}}>• {getLabel('386512',"如何用密保问题找回密码？")}</p>
  				<p style={{marginBottom: '12px'}}>{getLabel('386513',"您可以通过登录页面中的“忘记密码”选择“密保问题”验证答案，找回密码。")}</p>
  				<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6ez37z`} type='primary' onClick={() => {hrmPassword.doOpen('1');}}>{getLabel('386514',"立即设置")}</Button>
  			</div>
    )
  }

  pwdVerification(arg) {
    const {
      hrmPassword
    } = this.props;
    const {
      isSetted,
      secStatus,
      isModifyBtnClick,
      reDate,
    } = hrmPassword;
    const {
      pwd,
      openRSA
    } = this.state;
    const hrmId = this.props.params.hrmId || '';

    if (isSetted && !isModifyBtnClick) {
      if (!pwd || !this.vfyc) {
        message.error(getLabel('386497', "必填信息不完整！"));
        return false;
      }
       RSAEcrypt(openRSA, {
        password:pwd
      }).then(RSAParam => {
        hrmPassword.setSecutityStatus({pswd:RSAParam.password,validatecode:this.vfyc}, this.clearField);
       });
    }
    if (!isSetted || isModifyBtnClick) {
      if (!pwd || !this.vfyc) {
        message.error(getLabel('386497', "必填信息不完整！"));
        return false;
      }
      let RSAParam = {
        'password':pwd
      }
      RSAEcrypt(openRSA, RSAParam).then(RSAParam => {
        let params = {
          'id': hrmId,
          'pswd': RSAParam.password,
           validatecode:this.vfyc
        }
        WeaTools.callApi('/api/hrm/password/verifyPswd', 'POST', params).then((data) => {
          if (data.result == 'true') {
            hrmPassword.getTableEditInfo();
            hrmPassword.doOpen('2');
            hrmPassword.doClose('1');
            this.clearField();
          } else {
            reDate();
            if (data.message) {
              message.error(data.message);
            } else {
              message.error(getLabel('386525', "密码校验不通过，请重新输入！"));
            }
          }
        });
        hrmPassword.setPwdCopy(pwd);

      });
    }
  }

  clearField = () => {
     this.vfyc="";
    this.setState({
      pwd: ''
    });
  }

  getButtons() {
    const {
      hrmPassword
    } = this.props;
    const {
      current
    } = hrmPassword;
    let btns = [];
    const pre = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mibjj0`} type="primary" onClick={() => this.pre()} >{i18n.button.lastStep()}</Button>;
    const next = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7dspo2`} type="primary" onClick={() => this.next()} >{i18n.button.nextStep()}</Button>;
    const finish = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@k0l0x3`} type="primary" onClick={() => this.finish()} >{i18n.button.done()}</Button>;

    if (current == 0) {
      btns = [next];
    } else if (current == 1) {
      btns = [pre, next];
    } else {
      btns = [finish];
    }

    return btns;
  }

  pre() {
    const {
      hrmPassword
    } = this.props;
    const {
      current
    } = hrmPassword;
    this.props.form.resetFields();
    hrmPassword.minus();
  }

  next() {
    const {
      hrmPassword
    } = this.props;
    const {
      current,
      datasource
    } = hrmPassword;
    const {
      pwd
    } = this.state;

    if (current == 0) {
      if (datasource.length == 0) {
        message.error(getLabel('386515', "请填写密保问题！"));
        return false;
      } else {
        for (let i = 0; i < datasource.length; i++) {
          if (this.isEmptyObject(datasource[i])) {
            message.error(getLabel('386497', "必填信息不完整！"));
            return false;
          }
          for (let key in datasource[i]) {
            if (!('answer' in datasource[i]) || !('question' in datasource[i])) {
              message.error(getLabel('386497', "必填信息不完整！"));
              return false;
            }
            if (datasource[i][key] == '') {
              message.error(getLabel('386497', "必填信息不完整！"));
              return false;
            }
          }
        }
      }
    }
    if (current == 1) {
      let answerArray = [];
      let obj = this.props.form.getFieldsValue();
      for (let i in obj) {
        answerArray.push(obj[i]);
      }
      let b = this.securityAnswerVerification(answerArray);
      if (typeof b == 'number') {
        message.error(getLabel('24419', "问题 ") + b + getLabel('386516', " 输入的答案与问题不匹配，请重新输入！"));
        return false;
      } else {
        if (b) {
          let ds = toJS(datasource);
          let obj = {};
          for (let i = 0; i < ds.length; i++) {
            for (let key in ds[i]) {
              obj[key + '_' + i] = ds[i][key];
            }
          }
          hrmPassword.save(obj);
          this.props.form.resetFields();
        } else {
          message.error(getLabel('386497', "必填信息不完整！"));
          return false;
        }
      }
    }
    hrmPassword.plus();
  }

  finish() {
    const {
      hrmPassword
    } = this.props;
    const {
      isSetted
    } = hrmPassword;
    hrmPassword.doClose('2');
    hrmPassword.reset();
  }

  isEmptyObject(obj) {
    for (let key in obj) {
      return false;
    }
    return true;
  }

  securityAnswerVerification(answerArray) {
    const {
      hrmPassword
    } = this.props;
    const {
      datasource
    } = hrmPassword;
    let arr = [];
    let _arr = toJS(datasource);

    for (let i = 0; i < answerArray.length; i++) {
      if (!answerArray[i]) return false;
    }

    for (let i = 0; i < _arr.length; i++) {
      arr.push(_arr[i].answer);
    }
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] !== answerArray[i]) {

        return i + 1;
      }
    }
    return true;
  }

  getTableEdit() {
    const {
      hrmPassword
    } = this.props;
    let {
      columns,
      datasource
    } = hrmPassword;

    return (
      <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@4jgsv4`}
             columns={toJS(columns)}
             datas={toJS(datasource)}
             onChange={(arr) => hrmPassword.datasource = arr}
           />
    )
  }

  getQaForm() {
    const {
      hrmPassword
    } = this.props;
    const {
      datasource
    } = hrmPassword;
    const {
      getFieldDecorator,
      getFieldProps
    } = this.props.form;
    
    const tip = (
      <p>
        <i className="icon-coms-Explain" style={{color: "#faa825"}}/>
        <span style={{marginLeft: 10}}>{getLabel('386517',"以下是您刚刚设置的密保问题，请依次做出回答，以便进行确认")}</span>
      </p>
    )

    const Qa = (question,i) => {
      return (
        <div>
          <p>
            <span>
              {getLabel('24419',"问题 ")}:
            </span>
            <span>
              {question}
            </span>
          </p>
          <p>
            <span>{getLabel('24122',"答案")}:</span>
            <FormItem ecId={`${this && this.props && this.props.ecId || ''}_FormItem@lssr05`}>
              <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@d9z31q`} 
                {...getFieldProps('answer' + (i+1))} 
                {...getFieldDecorator('answer' + (i+1))}
                type="text" 
                viewAttr='3'
              />
            </FormItem>
          </p>
        </div>
      )
    }

    const arr = [];
    arr.push(tip);
   if (datasource.length) {
    datasource.forEach( (data,index) => {
      arr.push(Qa(data.question, index));
    })
   }
   return (
      <div className="hrm-pass-qa">
        <Form ecId={`${this && this.props && this.props.ecId || ''}_Form@9myso7`}>{arr}</Form>
      </div>
    );


    let _arr = [];
    _arr.push(
      <div style={{marginTop: '40px'}}>
  				<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@l63cok@1`}>
  					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@yqdwcq@1`} span={1} offset={5}>
  						<img src='/hrm/hrm_e9/image/wenhao.png' alt='' style={{width: '15px', height: '15px'}}/>
  					</Col>
  					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@m0h1dm@1`} span={13}>
  						<p>{getLabel('386517',"以下是您刚刚设置的密保问题，请依次做出回答，以便进行确认")}</p>
  					</Col>
  				</Row>	
  			</div>
    );

    for (let i = 0; i < datasource.length; i++) {
      _arr.push(<div style={{marginTop: '15px'}}>
  						<div style={{marginTop: '20px', width:420 ,marginLeft:113}}>
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@58oknx@${i}`}
                  label={getLabel('24419',"问题 ")}
                  labelCol={{span: 3, offset: 2}}
                  wrapperCol={{span: 19}}
                >
                  <p style={{marginTop: 4}}>{datasource[i].question}</p>
                </WeaFormItem>
  						</div>
  						<div style={{marginTop: '20px',width:420 ,marginLeft:113}}>
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@nu2jh9@${i}`}
                  label={getLabel('24122',"答案")}
                  labelCol={{span: 3, offset: 2}}
                  wrapperCol={{span: 19}}
                >
                  <FormItem ecId={`${this && this.props && this.props.ecId || ''}_FormItem@bhpxpx@${i}`}>
                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@hhbp07@${i}`} 
                      {...getFieldProps('answer' + (i+1))} 
                      {...getFieldDecorator('answer' + (i+1))}
                      type="text" 
                      viewAttr='3'
                    />
                  </FormItem>
                </WeaFormItem>
  						</div>
  					</div>);
    }

    return <Form ecId={`${this && this.props && this.props.ecId || ''}_Form@1egz04`}>{_arr}</Form>;
  }

  getFinishLogo() {
    return (
      <div style={{position: 'relative'}}>
          <div style={{position: 'absolute', top: 50, left: '50%', marginLeft: -92.5, width: 185}}>
              <img src='/hrm/hrm_e9/image/finish.png' alt='' />
          </div>
          <p style={{fontSize: '15px',paddingTop: 190,textAlign:'center'}}>{getLabel('386518',"您已完成了密保问题的设置!")}</p>
        </div>
    )
  }

  dropMenuDatasClick(key) {
    const {
      hrmPassword
    } = this.props;
    hrmPassword.doOpen('1');
    if (key == '3') hrmPassword.setModifyBtnStatus(false);
    if (key == '4') hrmPassword.setModifyBtnStatus(false);
    if (key == '5') hrmPassword.setModifyBtnStatus(true);
  }

  render() {
    const {
      hrmPassword
    } = this.props;
    const {
      tabKey,
      isPwdVerifyDialogShow,
      isPwdSecuritySettingShow,
      current,
      isSetted,
      secStatus,
      hrmId,
      showSecondaryPwd,
      showSecuritySetting,      
      date,
      reDate,
    } = hrmPassword;
    const {
      pwd,
      height,
    } = this.state;
    const btn1 = [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2ts290@1`} type="primary" onClick={() => this.pwdSave()}>{i18n.button.save()}</Button>),
    ]
    const btn2 = [
      (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1oorxd@2`} type="primary" onClick={() => this.pwdVerification()}>{i18n.button.nextStep()}</Button>),
    ]

    const dropMenuDatas = [{
      key: '0',
      content: i18n.button.save(),
      key: 'save',
      icon: <i className='icon-coms-Preservation' />,
      onClick: key => {
        this.pwdSave();
      }
    }, {
      key: '1',
      content: i18n.button.nextStep(),
      icon: <i className='icon-coms-Browse-box-Add-to' />
    }, {
      key: '2',
      content: getLabel('386514', "立即设置"),
      icon: <i className='icon-coms-currency' />
    }, {
      key: '3',
      content: getLabel('26472', "启用"),
      icon: <i className='icon-coms-operation' />
    }, {
      key: '4',
      content: getLabel('26471', "停用"),
      icon: <i className='icon-coms-locking' />
    }, {
      key: '5',
      content: getLabel('103', "修改"),
      icon: <i className='icon-coms-edit' />
    }, ]
    const dropMenuDatas1 = dropMenuDatas.slice(0, 1);
    const dropMenuDatas2 = dropMenuDatas.slice(1, 2);
    let dropMenuDatas3;
    if (!isSetted) dropMenuDatas3 = dropMenuDatas.slice(2, 3);
    if (isSetted && !secStatus) dropMenuDatas3 = dropMenuDatas.slice(3, 4);
    if (isSetted && secStatus) dropMenuDatas3 = dropMenuDatas.slice(4, 6);

    dropMenuDatas1.push({
      icon: <i className='icon-coms-Print-log'/>,
      content: i18n.button.log(),
      key: 'showLog',
      onClick: key => {
        window.setLogViewProps({
          logSmallType: i18n.smallType.HRM_PASSWPRD,
          targetId: hrmId
        });
      }
    })

    let tabName1 = [{
      key: '0',
      title: getLabel('518968', "登录密码")
    }, {
      key: '2',
      title: getLabel('501204', "二次验证密码")
    }, {
      key: '1',
      title: getLabel('81604', "密保设置")
    }]
    const dialogId = this.props.location.query.dialogId || '';

    if (dialogId != '') {
      tabName1 = [{
        key: '0',
        title: getLabel('81631', "密码修改")
      }]
    }
    if (!showSecondaryPwd) {
      if (tabName1.length > 1) {
        tabName1.splice(1, 1);
      }
    }
    if (!showSecuritySetting) {
      if (tabName1.length > 1) {
        const ssIndex = tabName1.findIndex(tab => tab.key === '1');
        (ssIndex > -1) && tabName1.splice(ssIndex, 1);
      }
    }

    return (
      <div className='hrm-password-bgcolor'>
  				<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@s32eh2`} 
            datas={ tabKey == '0' ? dropMenuDatas1 : dropMenuDatas3} 
            onClick={(key) => {tabKey == '0' ? '' : this.dropMenuDatasClick(key)}}
            collectParams={{favname: getLabel('20170',"密码设置"),favouritetype:5}}
          >
                  <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@7a4pri`} 
                  title={getLabel('20170',"密码设置")}
                  icon={<i className='icon-coms-hrm' />}
                  iconBgcolor='#217346'
                  loading={true}
                  buttons={tabKey == '0' && dialogId == '' ? btn1 : []}
                  showDropIcon={tabKey == '0' && dialogId == ''  ? true : false}
                  dropMenuDatas={dropMenuDatas1}
                  ></WeaTop>
          				<WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@crp93f`}
                  	selectedKey={tabKey}
                  	datas={tabName1}
                  	keyParam='key'
                  	onChange={(key) =>{hrmPassword.tabKey = key;['oldVal','newVal','confirmVal','verifyCode'].map(v => this.setState({[v]:''}))}} 
                	/>
                	{tabKey == '0' ? this.getPwdModificationGrid() : tabKey == '1' ?  this.getPwdSettingContent() : <SecondaryVerify ecId={`${this && this.props && this.props.ecId || ''}_SecondaryVerify@vn57mk`} />}
  				</WeaRightMenu>
  				
          <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@vk3p58`}
            	title={getLabel('504331',"请先输入登录密码")}
            	icon="icon-coms-hrm"
            	iconBgcolor="#217346"
            	visible={isPwdVerifyDialogShow}
            	onCancel={() => {hrmPassword.doClose('1'); this.setState({pwd: ''});this.vfyc=""}}
            	buttons={btn2}
            	style={{width: 600, height: 105}}
          > 
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@tlbtdv`} datas={dropMenuDatas2} onClick={() => this.pwdVerification()}>
          		<div style={{paddingTop: 15}}>
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@iv3q7e`}
                  label={getLabel('388431',"登录密码")}
                  labelCol={{span: 3, offset: 2}}
                  wrapperCol={{span: 13}}
                  style={{padding:"5px 0"}}
                >
                  <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@wi7roe`} 
                    type="password" 
                    viewAttr='3' 
                    value={pwd} 
                    onChange={(val) => this.setState({pwd: val})} 
                  />
                </WeaFormItem>
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@699yr5`}
                  label={getLabel('130021',"验证码")}
                  labelCol={{span: 3, offset: 2}}
                  wrapperCol={{span: 13}}
                  style={{padding:"5px 0"}}
                >
                  <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@5j6biw`} 
                    viewAttr='3' 
                    defaultValue="" 
                    onChange={(val) => this.vfyc = val} 
                  />
                  <img                   
                      src={`/weaver/weaver.file.MakeValidateCode?from=_changePass&isView=1&validatetype=0&validatenum=4&seriesnum_=${date}`}
                      style={{cursor:'pointer',display:'inline-block',marginLeft: 20,position:"absolute",top:-5}} 
                      onClick={reDate}
                  />
                </WeaFormItem>
          		</div>	
            </WeaRightMenu>
          </WeaDialog>
  				
          <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@f0jhln`}
            		title={getLabel('386520',"密保问题设置")}
            		icon="icon-coms-hrm"
            		iconBgcolor="#217346"
            		visible={isPwdSecuritySettingShow}
            		hasScroll={true}
            		onCancel={() => {hrmPassword.doClose('2'),hrmPassword.reset()}}
            		buttons={this.getButtons()}
            		style={{width: 720, height: 460}}
                onChangeHeight={(h) => this.setState({height: h})}
          		> 
          			<Steps ecId={`${this && this.props && this.props.ecId || ''}_Steps@ywldc9`} current={current} className="hrm-pwd-step-wrapper">
               			<Step ecId={`${this && this.props && this.props.ecId || ''}_Step@omolc6`} description={getLabel('386521',"填写密保问题")} />
               			<Step ecId={`${this && this.props && this.props.ecId || ''}_Step@3r8wye`} description={getLabel('386522',"验证密保问题")} />
               			<Step ecId={`${this && this.props && this.props.ecId || ''}_Step@2ilr60`} description={getLabel('386523',"完成密保问题")} />
            		</Steps>
            		<div ref="scrollBar">
              			<div className={`${current == 0? 'wea-show': 'wea-hide'}`}>
              			  {this.getTableEdit()}
              			</div>
              			<div className={`${current == 1? 'wea-show': 'wea-hide'}`}>
              			  {(current == 1) && this.getQaForm()}
              			</div>
              			<div className={`${current == 2? 'wea-show': 'wea-hide'}`}>
              			  {this.getFinishLogo()}
              			</div>
            		</div>	
          		</WeaDialog>
  			</div>
    )
  }
}

Password = Form.create({})(Password);

export default Password